<?php

namespace common\models;

use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use backend\models\UploadForm;
use common\components\OssSdk;

/**
 * This is the model class for table "{{%property}}".
 *
 * @property integer $id
 * @property string $thumbs
 * @property string $title
 * @property string $content
 * @property integer $open_at
 * @property integer $created_at
 * @property integer $updated_at
 */
class Property extends ActiveRecord
{

    // date must be datetime type 2017-10-10
    public $dateTime;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%property}}';
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
            ],
        ];
    
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'open_at'], 'required'],
            [['dateTime', 'content'], 'string'],
            [['open_at'], 'integer'],
            [['title'], 'string', 'max' => 255],
            [['thumbs'], 'string', 'skipOnEmpty' => true]
        ];
    }

    /**
     * ActiveRecord after find do somethin
     * 查询数据时给dateTime字段符格式化后的时间
     */
    public function afterFind()
    {
        $this->dateTime = date('Y-m-d H:i:s', $this->open_at);
        parent::afterFind();
    }

    /** 
     * 验证模型前
     * 处理dateTime当不是数字或数字字符串时，就认定为date类型
     * TODO 需要对date类型进行验证
     */
    public function beforeValidate()
    {
        $model = new UploadForm();
        $this->thumbs = $model->upload(); // 上传图片

        // thumbs空就删除这个属性
        if(empty($this->thumbs)) unset($this->thumbs);

        if (!is_numeric($this->dateTime)) {
            $this->open_at = strtotime($this->dateTime);
        }

        return parent::beforeValidate();
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'thumbs' => '图片',
            'title' => '楼盘名称',
            'content' => '楼盘介绍',
            'open_at' => '开盘时间',
            'created_at' => '添加时间',
            'updated_at' => '更新时间',
        ];
    }
}
